﻿// Copyright (c)  YISH. All rights reserved.
// Licensed under the MIT License, See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using NSQL.Sharpen;

namespace NSQL.Expressions
{
    public class MatchExpression : BaseExpression, IMatchExpression
    {
        public IList<MatchPair<IPredicateExpression, IExpression>> Matches { get; } =
            new List<MatchPair<IPredicateExpression, IExpression>>();

        public IExpression Default { get; set; }

        public MatchExpression(IEnumerable<MatchPair<IPredicateExpression, IExpression>> matches,
            IExpression defaultValue)
        {
            foreach (var match in matches)
            {
                Matches.Add(match);
            }

            Default = defaultValue;
        }


        public override T Accept<T>(IExpressionVisitor<T> visitor) => visitor.Visit(this);
        public override void Accept(IExpressionVisitor visitor) => visitor.Visit(this);
        public override bool IsValid => Default.IsValid &&Matches.All(o => o.Then.IsValid && o.When.IsValid);
        protected override IExpression DeepCopy()
        {
            return new MatchExpression(
                Matches.Select(o => new MatchPair<IPredicateExpression, IExpression>
                {
                    Then = o.Then,
                    When = o.When
                }).ToList(), Default.DeepClone())
            {
                Tag = Tag
            };
        }
    }
}